package com.wei.web.filter;

import com.wei.utils.ApplicationConstants;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class RequestWrapperFilter implements Filter {

    //Filter可以拿到WebApplicationContext得到IOC容器
    //private WebApplicationContext context = null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //ServletContext servletContext = filterConfig.getServletContext();
        //context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // TODO 需要验证一下 如果是一个servlet请求,并且是个POST请求,才进行封装
        if(servletRequest instanceof  HttpServletRequest
        && ApplicationConstants.POST.equals(((HttpServletRequest)servletRequest).getMethod())) {
            RequestWrapper wrapper = new RequestWrapper((HttpServletRequest) servletRequest);
            filterChain.doFilter(wrapper, servletResponse);
        }else{
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
        //context=null;
    }
}
